package main

import (
	"fmt"
	stream "go_final/demos/grpc_stream/myproto"
	"net"
	"sync"
	"time"

	"google.golang.org/grpc"
)

const PORT = ":50052"

type Server struct {
	stream.UnimplementedGreaterServer
}

func (s *Server) GetStream(req *stream.GetStreamRequest, res stream.Greater_GetStreamServer) error {
	i := 0
	for {
		i++
		_ = res.Send(&stream.GetStreamResponse{
			Data: fmt.Sprintf("This is the No: %d message.proto  from server", i),
		})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}

func (s *Server) PostStream(cliStr stream.Greater_PostStreamServer) error {
	for {
		a, err := cliStr.Recv()
		if err != nil {
			fmt.Println("err: ", err)
			break
		}
		fmt.Println("a: ", a)
	}
	return nil
}

func (s *Server) AllStream(allStr stream.Greater_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			println("Get message.proto forms client: ", data.Data)
		}
	}()

	go func() {
		defer wg.Done()
		i := 0
		for {
			i++
			allStr.Send(&stream.GetStreamResponse{
				Data: fmt.Sprintf("This is the No: %d message.proto  from server", i),
			})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	return nil
}

func main() {
	// 1. 监听端口
	listener, err := net.Listen("tcp", PORT)
	if err != nil {
		panic("failed to listen: " + err.Error())
	}

	// 2.新建一个serve
	s := grpc.NewServer()

	// 3.注册服务
	stream.RegisterGreaterServer(s, &Server{})

	_ = s.Serve(listener)
}
